<?php
namespace app\beautiful\controller\miniapp\staff;
use app\BaseController;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\logs\StoreWriteOffModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\StoreOrderModel;
use think\facade\Db;

class StoreOrder extends BaseController {
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        if (!in_array(6, $this->request->staff->add_value_jurisdiction)) {
            $this->error('您没有囤货订单管理的权限')->send();
            die();
        }
    }

    public function getStoreOrderList(){
        $status = $this->request->param('status/d');
        $mobile=$this->request->param('mobile');
        $member_id=$this->request->param('member_id/d',0);
        $return = [];
        $where = [
            ['shop_id','=', $this->request->shopId],
            ['is_delete','=',0]
        ];
        $member_where=[
            ['shop_id','=',$this->request->shopId]
        ];
        if($member_id != 0){
            if(null !== $member = MemberModel::find($member_id)){
                $return['member']=[
                    'member_id'=>$member->member_id,
                    'mobile'=>$member->mobile,
                ];
            }
            $member_where[]=['member_id','=',$member_id];
        }else{
            if(!empty($mobile)){
                $member_where[]=['mobile','=',$mobile];
            }
        }
        $member_ids= MemberModel::where($member_where)->column('member_id') ?? [];
        $where[]=['member_id','in',$member_ids];
        switch ($status){ //查询订单的状态
            case 0: // 待付款
                $where[] = ['status','=',1];
                break;
            case 1://待自提
                $where[] = ['status','=',4];
                break;
            case 2://已完成  取消的订单也在已完成里面
                $where[] = ['status','=',8];
                break;
            case 3:
                $where[] = ['status','=',-1];
                break;
        }
        $datas = StoreOrderModel::with(['member'=>function($query){
            $query->field('member_id,nick_name,mobile')->append(['hidden_mobile']);
        }])->where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order(['store_order_id'=>'desc'])
            ->select()->hidden(['pay_info'])->append(['order_time','djs_time','remain_num'])
            ->toArray();
        $return['datas']=$datas;
        return $this->success($return);
    }

    public function detail()
    {
        $store_order_id = $this->request->param('store_order_id/d',0);
        if($store_order_id==0) return $this->error('订单不存在#1');
        if(null === $store_order = StoreOrderModel::find($store_order_id)) return $this->error('订单不存在#2');
        if($store_order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if($store_order->is_delete != 0) return $this->error('订单不存在#4');

        if(null === $member = MemberModel::find($store_order->member_id)) return $this->error('订单不存在#5');
        if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');
        $member->append(['hidden_mobile']);

        $store_order->append(['add_time_format','pay_time_format','status_means','pay_type_mean','gift_total_price','remain_num']);



        $detail=[
            'store_order_id'=>$store_order->store_order_id,
            'add_time_format'=>$store_order->add_time_format,
            'status'=>$store_order->status,
            'status_means'=>$store_order->status_means,
            'need_pay'=>$store_order->need_pay,
            'pay_type'=>$store_order->pay_type,
            'pay_type_mean'=>$store_order->pay_type_mean,
            'pay_time_format'=>$store_order->pay_time_format,
            'goods_total_price'=>$store_order->goods_total_price,
            'goods_worth'=>$store_order->goods_worth,
            'youhui_balance'=>$store_order->youhui_balance,
            'member_name'=>$member->nick_name,
            'member_mobile'=>$member->mobile,
            'member_hidden_mobile'=>$member->hidden_mobile,
            'goods_name'=>$store_order->goods_name,
            'goods_cover_img'=>$store_order->goods_cover_img,
            'goods_num'=>$store_order->goods_num,
            'remain_num'=>$store_order->remain_num,
            'goods_gift_giving'=>$store_order->goods_gift_giving,
            'gift_total_price'=>$store_order->gift_total_price,
            'write_off_logs'
        ];

        return $this->success(['detail'=>$detail]);
    }

    public function getWriteOffLogs()
    {

        $store_order_id = $this->request->param('store_order_id/d',0);
        if($store_order_id==0) return $this->error('订单不存在#1');
        if(null === $store_order = StoreOrderModel::find($store_order_id)) return $this->error('订单不存在#2');
        if($store_order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if($store_order->is_delete != 0) return $this->error('订单不存在#4');

        if(null === $member = MemberModel::find($store_order->member_id)) return $this->error('订单不存在#5');
        if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');


        $write_off_logs=StoreWriteOffModel::where([
            ['shop_id','=',$this->request->shopId],
            ['store_order_id','=',$store_order_id],
        ])->select()->append(['add_time_format','operate_hidden_mobile'])->toArray();

        return $this->success(['datas'=>$write_off_logs]);
    }

    public function writeOffStoreOrder()
    {
        $store_order_id = $this->request->param('store_order_id/d',0);
        $num = $this->request->param('num/d',0);
        $remarks=$this->request->param('remarks');
        if($store_order_id==0) return $this->error('订单不存在#1');
        if($num <= 0) return $this->error('请选择核销数量');


        if(null === $store_order = StoreOrderModel::find($store_order_id)) return $this->error('订单不存在#2');
        if($store_order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');
        if($store_order->is_delete != 0) return $this->error('订单不存在#4');
        if($store_order->status !=4 ) return $this->error('订单无法进行核销');
        $write_off_num=$store_order->write_off_num + $num;
        if($write_off_num > $store_order->goods_num) return $this->error('核销数量不够');

        if(null === $member = MemberModel::find($store_order->member_id)) return $this->error('订单不存在#5');
        if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');

        Db::startTrans();
        try{
            //订单操作
            $store_order->write_off_num=$write_off_num;
            if($write_off_num >= $store_order->goods_num) $store_order->status=8;
            $store_order->save();

            //插入一条消费记录
            $remain_num=$store_order->goods_num-$store_order->write_off_num;
            $res=LogsLogic::storeOrder($this->request->shopId,$member->member_id,1,$store_order_id,$num,$remain_num,$remarks,$this->request->staffId);

            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('storeOrderWriteOff',$res);

            Db::commit();
            return $this->success('核销成功');

        }catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function cancelOrder()
    {
        $store_order_id=$this->request->param('store_order_id/d',0);
        $order=StoreOrderModel::find($store_order_id);
        if(null === $order) $this->error('订单不存在');
        $params=[
            'order_id'=>$store_order_id,
            'member_id'=>$order->member_id,
        ];
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic['store']->cancelOrder($params);
            Db::commit();
            return $this->success('成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
}
